/**
 * Created by joy on 03/09/2017.
 */

import BitcoinCashWalletHelper from '../../common/helpers/chain/BitcoinCashWalletHelper'
import CommonUtil from '../../common/utils/CommonUtil'
import prompt from 'prompt'
import BitcoinRpcHelper from '../../common/helpers/chain/BitcoinRpcHelper'
import HttpRequestHelper from '../../common/helpers/HttpRequestHelper'

export default () => {
  return new Promise(async (resolve, reject) => {
    try {
      const bitcoinCashWalletHelper = new BitcoinCashWalletHelper()
      const httpRequestHelper = new HttpRequestHelper()
      const schema = {
        properties: {
          host: {
            description: 'Enter host of node',
            type: 'string',
            required: true,
            default: '127.0.0.1'
          },
          port: {
            description: 'Enter port of node',
            type: 'number',
            required: true,
            default: 18332
          },
          user: {
            description: 'Enter rpc user of node',
            type: 'string',
            required: true,
            default: 'test'
          },
          password: {
            description: 'Enter rpc password of node',
            type: 'string',
            hidden: true,
            replace: '*',
            required: true,
            default: '123456789'
          }
        }
      }

      const args = await CommonUtil.getArgsFromConsole(prompt, schema)
      const { host, port, user, password } = args
      const bitcoinRpcHelper = new BitcoinRpcHelper(host, port, user, password)
      const result = await bitcoinRpcHelper.resendWalletTransactions()
      logger.info(result)
      logger.info('广播成功')
      // const txRestResult = await httpRequestHelper.getJson(`http://${host}:${port}${config['mempoolContentUrl']}`)
      // // 按ancestorcount数量排序
      // const txToBroadcasts = Object.entries(txRestResult).sort(([key1, value1], [key2, value2]) => {
      //   return value1['ancestorcount'] - value2['ancestorcount']
      // })
      // // 广播
      // const bitcoinRpcHelper = new BitcoinRpcHelper(host, port, user, password)
      // for (let txToBroadcast of txToBroadcasts) {
      //   const [txid, data] = txToBroadcast
      //   const txHex = await bitcoinRpcHelper.getRawTransaction(txid)
      //   await bitcoinRpcHelper.sendRawTransaction(txHex)
      //   logger.info(`${txid} 广播成功`)
      //   // break
      // }
    } catch (err) {
      logger.error(err)
      reject(err)
    }
  })

}
